package project.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import project.model.Question;
import project.model.User;
import project.service.QuestionService;

import java.time.LocalDateTime;
@CrossOrigin
@RequestMapping(value = "/question")
@RestController
public class QuestionController {
    @Autowired
    QuestionService questionService;
    @Autowired
    RedisTemplate redisTemplate;
    @PostMapping
    public int addQuestion(@ModelAttribute Question question,@RequestParam String loginName) {
        System.out.println("Question added successfully");
        question.setCreate_time(String.valueOf(LocalDateTime.now()));
        question.setUpdate_time(String.valueOf(LocalDateTime.now()));

        Integer idInt = (Integer) redisTemplate.opsForHash().get(loginName, "uid");
        if (idInt!=null)question.setUid(idInt);
        questionService.addQuestion(question);
        int tid=question.getTid();
        return tid;
    }

//    @GetMapping(value = "/list/{uid}")
//    public Question[] getQuestionListByUserId(@PathVariable String uid) {
//        System.out.println("Question list get successfully!");
//        Integer idInt =uid==null?0:Integer.parseInt(uid);
//        String loginName=(String)redisTemplate.opsForValue().get("loginName");
//        if (loginName!=null){
//            return questionService.getQuestionListByUserId(idInt);
//        }else return null;
//
//    }
    @GetMapping(value = "/list")
    public Question[] getQuestionListByUserId(@RequestParam String loginName) {
        System.out.println("Question list get successfully!");
        Integer idInt = (Integer) redisTemplate.opsForHash().get(loginName, "uid");
        if (idInt!=null){
            return questionService.getQuestionListByUserId(idInt);
        }else return null;

    }

    @GetMapping(value = "/{tid}")
    public Question getQuestionById(@PathVariable String tid) {
        System.out.println("Question get successfully!");
        Integer idInt =tid==null?0:Integer.parseInt(tid);
        return questionService.getQuestionById(idInt);
    }
    @PutMapping
    public int updateQuestion(@ModelAttribute Question question) {
        System.out.println("Question updated successfully!");
        question.setUpdate_time(String.valueOf(LocalDateTime.now()));
        return questionService.updateQuestion(question);
    }
    @DeleteMapping
    public int deleteUser(@RequestParam String tid) {
        System.out.println("Question deleted successfully!");
        Integer idInt =tid==null?0:Integer.parseInt(tid);

        return questionService.deleteQuestion(idInt);
    }
















}







